#include "Game.h"

IGame* createGame( HINSTANCE hInst, HWND hWnd )
{
	return new Game( hInst, hWnd );
}

Game::Game( HINSTANCE hInst, HWND hWnd ) :
	m_input( hInst, hWnd )
{
	// initialize camera
	m_camera.hand = Camera::RIGHTHANDED;

	m_camera.eye = float3( 0, 0, 20.f );
	m_camera.at  = float3( 0, 0, 0 );
	m_camera.up  = float3( 0, 1, 0 );

	m_camera.projectionType = Camera::PERSPECTIVE_FOV;
	m_camera.perspectiveFov.fovy = D3DXToRadian(45.f);
	m_camera.perspectiveFov.aspect = 1024.f/768.f;

	m_camera.zn = 1.0f;
	m_camera.zf = 100.0f;
}

Game::~Game()
{
	m_d3dDevice = 0;
}

void Game::onCreateGraphics( D3DDevice device )
{
	m_d3dDevice = device;

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 world = identity44();
	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_WORLD, &world );
	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );

	// initialize polygon shapes
	poly::Polygon triangle;
	triangle.push_back( float3( cos(0.f), sin(0.f), 0 ) );
	triangle.push_back( float3( cos(TWO_PI/3), sin(TWO_PI/3), 0 ) );
	triangle.push_back( float3( cos(2*TWO_PI/3), sin(2*TWO_PI/3), 0 ) );

	poly::Polygon ground;
	ground.push_back( float3( 5, -5, 0 ) );
	ground.push_back( float3( -5, 0, 0 ) );
	ground.push_back( float3( 0, -5, 0 ) );

	// initialize rigid poly's
	m_poly.setup( device, triangle, float4( 1.f, 0.5f, 0.6f, 0.3f ) );
	m_poly.rigidBody.friction = 5.f;
	m_poly.rigidBody.elasticity = 0.1f;
	m_ground.setup( device, ground, float4( 1.f, 0.3f, 0.4f, 0.1f ) );

	m_ground.rigidBody.invMass = 0.f;
	m_ground.rigidBody.invLocalInertia = zero33();
	m_ground.rigidBody.friction = 1.f;
	m_ground.rigidBody.elasticity = 0.5f;

	m_poly.rigidBody.pos = float3( 0, 2, 0 );

	// initialize constraint
	m_collision.colliders.insert( &m_ground );
	m_collision.colliders.insert( &m_poly );

	// initialize dynamics
	m_dynamics.constraints.insert( &m_collision );
	m_dynamics.dynObjects.insert( &m_ground );
	m_dynamics.dynObjects.insert( &m_poly );
}

void Game::onResetGraphics( D3DDevice device )
{
	//TODO: Add code to handle lost device ( resizing issue )

	m_d3dDevice = device;

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onLostGraphics()
{
}

void Game::onFrameMove(float dt)
{
	IInput::MOUSESTATE ms;
	ms = m_input.mouseState();
	m_poly.rigidBody.addForce( float3( 0, -1, 0 ) );
	m_poly.rigidBody.addTorque( float3( 0, 0, (ms.buttons[0] - ms.buttons[1])*0.01f ) );

	m_dynamics.step(dt);
}

void Game::onFrameRender(float dt)
{
	m_dynamics.render(dt);
}

void Game::onDestroyGraphics()
{
}
